package com.tdcy.framework.util;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Encoder;

public class DesUtil {

	public static String desDecoder(String data, String scret) {
		try {
			byte[] byteMi = new sun.misc.BASE64Decoder().decodeBuffer(data);
			IvParameterSpec iv = new IvParameterSpec(scret.getBytes("UTF-8"));
			SecretKeySpec key = new SecretKeySpec(scret.getBytes("UTF-8"), "DES");
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, key, iv);
			byte decryptedData[] = cipher.doFinal(byteMi);
			return new String(decryptedData);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//通用C#加密
	public static String desEncrypt(String message, String key){
		Cipher cipher;
		try {
			cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
			BASE64Encoder encoder = new BASE64Encoder();
			String msg = encoder.encode(cipher.doFinal(message.getBytes("UTF-8")));
	       // String msg = parseByte2HexStr(cipher.doFinal(message.getBytes("UTF-8")));
			return msg;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return message;
		}
	}
	
	public static void main(String[] args) {
		String r = "123456";
		r = desEncrypt(r,"abcde@gh");
		System.out.println(r);
		r = desDecoder(r,"abcde@gh");
		System.out.println(r);
	}
}
